package com.shipwe.loans.ui.presenter

import com.shipwe.loans.MyApps
import com.shipwe.loans.R
import com.shipwe.loans.http.ApiService
import com.shipwe.loans.http.ApiService.addCommonParams
import com.shipwe.loans.http.IHttpCallback
import com.shipwe.loans.pro.ShipwePresenter
import com.shipwe.loans.ui.view.IMainView
import com.shipwe.loans.utils.ShipweDateUtil
import com.shipwe.loans.utils.event.AppEventData
import com.shipwe.loans.utils.helper.CustomConfigsHelper
import com.shipwe.loans.utils.helper.CustomProcessHelper
import com.shipwe.loans.utils.helper.UserPointsHelper
import com.shipwe.loans.utils.shared.ShipweSharedHelper
import com.shipwe.loans.utils.shared.ShipweSharedKey
import org.json.JSONObject

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/22 11:59
 * @Annotation：主页面 Presenter 实现
 */
class MainPresenter(private val iView: IMainView): ShipwePresenter(iView) {
    //val 是不可变的 var 可变的
    private val mainTabList = arrayListOf(
        R.drawable.page_home_icon,
        R.drawable.page_repayment_icon,
        R.drawable.page_luckydraw_icon
    )
    private val mainTabTitleList = arrayListOf(
        R.string.main_tab_home,
        R.string.main_tab_repayment,
        R.string.main_tab_lucky_draw
    )
    //定义tab的每个页面
    private val tabList = arrayListOf<JSONObject>()
    var curtIndex = -1
    /**
     * 加载Tabbar数据
     */
    fun loadMainTabList(){
        tabList.clear()
        //tab
        for (i in 0 until mainTabList.size) {
            val tabObj = JSONObject()
            tabObj.put("tabId", i)
            tabObj.put("mainTabIcon", mainTabList[i])
            tabObj.put("mainTabTitle", getString(mainTabTitleList[i]))
            tabObj.put("isSelect", false)
            tabList.add(tabObj)
        }
        iView.showMainTabList(tabList)
    }

    /**
     * 切换Tab
     */
    fun setMainCurrentItemIndex(index: Int) {
        curtIndex = index
        for (tabObj in tabList) {
            when (tabObj.optInt("tabId")) {
                index -> {
                    tabObj.put("isSelect", true)
                }
                else -> {
                    tabObj.put("isSelect", false)
                }
            }
        }
        iView.notifyMainTabDataChanged(index)
        if (index == 0){
            //获取签到信息
            getMainUserSignInfoAction()
        }
    }

    /**
     * 获取总流程
     */
    fun loadAppProcessAction() {
        val httpUrl = ApiService.getHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", ApiService.API_PATH.SHIPWE_API_PROCESS_PATH)
        }
        doHttpPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                //保存用户流程状态
                if (obj != null) {
                    // TODO: 测试添加 Step 类型
//                    val allStepTitles = obj.optJSONArray("allStepTitles")
//                    allStepTitles.put("Ocr Info")
//                    allStepTitles.put("Face recognition")
//                    allStepTitles.put("Account Info")
//                    val allSteps = obj.optJSONArray("allSteps")
//                    allSteps.put("ocr_info")
//                    allSteps.put("sefie_info")
//                    allSteps.put("account_info")
//                    val steps = obj.optJSONArray("steps")
//                    steps.put("sefie_info")
//                    val index = Random.nextInt(3)
//                    when(index){
//                        0 -> {
//                            steps.put("ocr_info")
//                        }
//                        1 -> {
//                            steps.put("sefie_info")
//                        }
//                        else -> {
//                            steps.put("account_info")
//                        }
//                    }
                    //保存用户流程数据
                    CustomProcessHelper.saveAuthProcessData(obj)
                    //通知全局流程刷新完成
                    iView.getAct().publishEventData(AppEventData(AppEventData.TYPE.SHIPWE_PROCESS_REFRESHED))

                    // TODO: 2024-11-20 新增需求 此处需要判断是否需要校验手机号
                    if (CustomProcessHelper.isCheckWhatsApp() || CustomProcessHelper.isCheckSMS()){
                        iView.showMainCheckNumberPage()
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 获取产品列表
     * 存在待还款的产品 ，需要直接展示Repay，否则显示可申请产品列表
     */
    fun loadAppProductListAction(){
        val params = JSONObject()
            .addCommonParams()
            .apply {
                put("path", ApiService.API_PATH.SHIPWE_API_LOAN_PRODUCT_LIST_PATH)
                put("mobile", ShipweSharedHelper.getShipweSharedString(ShipweSharedKey.SHIPWE_MOBILE))
            }
        val httpUrl = ApiService.getHttpUrl()
        doHttpPostAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                ShipweSharedHelper.putShipweSharedData(ShipweSharedKey.SHIPWE_PRODUCT,data.optString("obj"))
                iView.getAct().publishEventData(AppEventData(AppEventData.TYPE.SHIPWE_PRODUCT_REFRESHED))

                var showTabIndex = 0
                val objArray = data.optJSONArray("obj")
                if (objArray != null) {
                    //可申请的产品数量
                    var productCount = 0
                    for (i in 0..<objArray.length()){
                        val item = objArray.optJSONObject(i)
                        //可申请的产品
                        if (item.optString("activeFlag") == "YES"){
                            productCount++
                        }

                        if ("REPAYMENT" == item.optString("status")){
                            showTabIndex = 1
                        }
                    }
                    //保存用户VIP等级
                    saveAppUserVip(productCount)
                }
            }

            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                iView.getAct().publishEventData(AppEventData(AppEventData.TYPE.SHIPWE_PRODUCT_FINISHED))
            }
        })
    }

    /**
     * 获取签到信息
     * signType:
     *          getSignInfo - 查询用户签到信息
     *          userSignIn - 保存用户签到信息
     */
    fun getMainUserSignInfoAction(){
        val httpUrl = ApiService.getHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path",ApiService.API_PATH.SHIPWE_API_SIGN_PATH)
            put("mobile", ShipweSharedHelper.getShipweSharedString(ShipweSharedKey.SHIPWE_MOBILE))
            put("signType","getSignInfo")
        }
        doHttpPostAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null){
                    obj.put("lastSignTime",obj.optString("lastSignTime").replace("-",""))
                    //保存用户签到信息
                    ShipweSharedHelper.putShipweSharedData(ShipweSharedKey.SHIPWE_SIGN_INFO,obj.toString())
                    //刷新积分完成
                    iView.getAct().publishEventData(AppEventData(AppEventData.TYPE.SHIPWE_POINTS_REFRESHED))

                    //上次签到时间
                    val lastSignTime = obj.optString("lastSignTime")
                    //连续签到天数
                    val conSignTime = obj.optString("conSignTime")

                    //没有签到时间 - 没有签过到
                    if (lastSignTime.isEmpty() || "0" == lastSignTime){
                        setMainUserSignAction("1")
                    } else {
                        //签过到
                        //上次签到时间是否是今天
                        if (ShipweDateUtil.IsToday(lastSignTime.toLong() * 1000)){
                            //签过到了
                        } else {
                            //上次签到时间是否是昨天
                            if (ShipweDateUtil.IsYesterday(lastSignTime.toLong() * 1000)){
                                //连续签到天数 +1
                                setMainUserSignAction("${conSignTime.toInt() + 1}")
                            } else {
                                //非连续签到： 连续签到天数 1
                                setMainUserSignAction("1")
                            }
                        }
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 签到
     */
    fun setMainUserSignAction(conSignTime: String){
        val httpUrl = ApiService.getHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path",ApiService.API_PATH.SHIPWE_API_SIGN_PATH)
            put("mobile", ShipweSharedHelper.getShipweSharedString(ShipweSharedKey.SHIPWE_MOBILE))
            put("signType","userSignIn")
            put("signDate", System.currentTimeMillis() / 1000)//签到时间戳
            put("conSignTime", conSignTime)//连续签到天数
        }
        doHttpPostAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null){
                    // 连续签到增加积分数
                    val signPoints = CustomConfigsHelper.getShipweSignPointsBySignTime(conSignTime.toInt())
                    //弹窗签到成功dialog
                    iView.showMainSignSuccessDialog(signPoints)
                    //签到成功 存储签到积分
                    UserPointsHelper.onSaveUserPointsAction("signPoints",MyApps.app.getString(R.string.points_use_info_check_in),signPoints)
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 保存用户Vip等级
     */
    fun saveAppUserVip(pCount: Int){
        if (pCount <= 1){
            ShipweSharedHelper.putShipweSharedData(ShipweSharedKey.SHIPWE_VIP,1)
        } else if (pCount > 4){
            ShipweSharedHelper.putShipweSharedData(ShipweSharedKey.SHIPWE_VIP,3)
        } else {
            ShipweSharedHelper.putShipweSharedData(ShipweSharedKey.SHIPWE_VIP,2)
        }
    }
}